package org.example.demo1;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  三个线程轮流执行，精确地通知
 */
public class pc2_changed {
    public static void main(String[] args) {
        OWNData ownData = new OWNData();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ownData.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ownData.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ownData.printC();
            }
        },"C").start();

    }
}
class OWNData{
    Lock lock = new ReentrantLock();
    Condition condition_A = lock.newCondition();
    Condition condition_B = lock.newCondition();
    Condition condition_C = lock.newCondition();
     private int number = 1; // 1A 2B 3C
    public  void  printA(){
        lock.lock();
        try {
            // 判断是否等待
            while ( number != 1){
                condition_A.await();
            }
            // 业务
            System.out.println(Thread.currentThread().getName()+"--->"+"AAAAAA");
            // 唤醒线程二
            number=2;
            condition_B.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public  void  printB(){
        lock.lock();
        try {
            // 判断是否等待
            while ( number != 2){
                condition_B.await();
            }
            // 业务
            System.out.println(Thread.currentThread().getName()+"--->"+"BBBBBB");
            // 唤醒线程二
            number= 3;
            condition_C.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public  void  printC(){
        lock.lock();
        try {
            // 判断是否等待
            while ( number != 3){
                condition_C.await();
            }
            // 业务
            System.out.println(Thread.currentThread().getName()+"--->"+"CCCCCC");
            // 唤醒线程二
            number= 1;
            condition_A.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
